package com.wch.sqlSession;

import com.wch.config.BoundSql;
import com.wch.pojo.Configuration;
import com.wch.pojo.MappedStatement;
import com.wch.utils.GenericTokenParser;
import com.wch.utils.ParameterMapping;
import com.wch.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        //注册驱动
        Connection connection = configuration.getDataSource().getConnection();
        //获取PreparedStatement  存储的sql语句为select * from user where id = #{id} and username=#{username}
        //将sql转换
        String sqlT = mappedStatement.getSql();
        BoundSql sql = getBoundSql(sqlT);
        PreparedStatement preparedStatement = connection.prepareStatement(sql.getParseSql());

        //设置参数
        SetParams(sql,mappedStatement,params,preparedStatement);

        //执行sql
        ResultSet resultSet = preparedStatement.executeQuery();

        //封装结果集
        List list = SetResult(mappedStatement, resultSet);

        //关闭连接
        resultSet.close();
        preparedStatement.close();
        connection.close();

        //返回list
        return list;
    }

    @Override
    public Boolean update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        //注册驱动
        Connection connection = configuration.getDataSource().getConnection();
        //获取PreparedStatement  存储的sql语句为select * from user where id = #{id} and username=#{username}
        //将sql转换
        String sqlT = mappedStatement.getSql();
        BoundSql sql = getBoundSql(sqlT);
        PreparedStatement preparedStatement = connection.prepareStatement(sql.getParseSql());
        //设置参数
        SetParams(sql,mappedStatement,params,preparedStatement);

        //执行sql
        boolean flag=false;
        int i = preparedStatement.executeUpdate();

        if (i==1){
            flag=true;
        }

        //关闭连接
        preparedStatement.close();
        connection.close();

        //返回结果
        return flag;
    }

    /**
     * 根据参数对应实体类路径通过反射找到实体类
     * @param paramterType 参数所对应的实体类路径
     * @return 对应实体类
     * @throws ClassNotFoundException 类无法找到异常
     */
    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        if (paramterType!=null){
            return Class.forName(paramterType);
        }else{
            return null;
        }
    }

    /**
     * 完成对#{}的解析工作：1.将#{}使用？进行代替，2.解析出#{}里面的值进行存储
     * @param sqlT xml中写的sql语句
     * @return     含有  jdbc可以识别的sql语句、参数集合
     */
    private BoundSql getBoundSql(String sqlT) {
        //标记处理类：配置标记解析器来完成对占位符的解析处理工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        //解析出来的sql
        String parseSql = genericTokenParser.parse(sqlT);
        //#{}里面解析出来的参数名称
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();

        return new BoundSql(parseSql,parameterMappings);
    }
    /**
     * 为preparedStatement设置参数
     * @param sql 转换后sql
     * @param mappedStatement 封装的map对象
     * @param params  传入的对象
     * @param preparedStatement preparedStatement
     * @throws Exception 抛出异常
     */
    private void SetParams(BoundSql sql, MappedStatement mappedStatement, Object[] params, PreparedStatement preparedStatement) throws Exception {
        List<ParameterMapping> parameterMappings = sql.getParameterMappings();
        //获取到实体类的全路径
        String paramterType = mappedStatement.getParamterType();
        //通过实体类的全路径获取到实体类
        Class<?> paramterTypeClass = getClassType(paramterType);
        for (int i = 0; i < parameterMappings.size(); i++) {

            //从一个select标签中获取到每一个参数名
            String content = parameterMappings.get(i).getContent();
            //通过反射 获取到实体类中的属性
            Field declaredField = paramterTypeClass.getDeclaredField(content);
            //设置暴力访问
            declaredField.setAccessible(true);
            //params[0]为获取到封装对象 测试时传入 o为每一个属性
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i+1,o);
        }
    }

    /**
     * 返回结果集
     * @param mappedStatement 封装的map对象
     * @param resultSet     结果集
     * @return              集合list
     * @throws Exception    抛出异常
     */
    private List<Object> SetResult(MappedStatement mappedStatement,ResultSet resultSet) throws Exception {
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);

        ArrayList<Object> objects = new ArrayList<>();
        while (resultSet.next()){
            Object o = resultTypeClass.newInstance();
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {

                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段的值
                Object value = resultSet.getObject(columnName);

                //使用反射或者内省，根据数据库表和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o,value);
            }
            objects.add(o);
        }
        return objects;
    }
}
